<template>
  <el-button type="primary" v-per2="['user-list','post']" @click="doAddUser">新增用户</el-button>
  <el-row style="margin-top:20px;">
    <el-table :data="state.tableData" border style="width: 100%" v-loading="state.isLoading"
              v-per2="['user-list','get']">
      <el-table-column prop="username" label="用户名"/>
      <el-table-column prop="is_super" label="是否超级用户">
        <template #default="scope">
          <el-tag v-if="scope.row.is_super" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="role_display" label="角色">
        <template #default="scope">
          <el-tag style="margin-right: 5px" type="primary" v-for="item in scope.row.role_display" :key="item.id">
            {{ item.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="is_super" label="重置密码">
        <template #default="scope">
          <el-link :icon="Edit" @click="doResetPwd">重置密码</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="操作">
        <template #default="scope">
          <el-popconfirm
              cancel-button-type="danger"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="confirmUserDelete(scope.row)"
              title="确认删除吗?">
            <template #reference>
              <el-button type="danger" size="small" icon="Delete" class="card-small-btn"></el-button>
            </template>
          </el-popconfirm>
          <el-button type="success" size="small" icon="Edit" class="card-small-btn"
                     @click="doUserEdit(scope.row,scope.$index)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px">
      <el-pagination
          :total="state.page.totalCount"
          :page-size="state.page.perPageSize"
          background
          layout="prev, pager, next,jumper"
          @current-change="handleChangePage">
      </el-pagination>
    </div>
  </el-row>
  <MineDialog :obj="state.userAddDialog"></MineDialog>
  <MineDialog :obj="state.userEditDialog"></MineDialog>
</template>

<script setup>
import {onMounted, reactive} from "vue";
import _axios from "@/plugin/axios.js";
import {ElMessage} from "element-plus";
import MineDialog from "@/components/DialogDouble.vue";
import {hasPermission2} from "@/stores/permission.js";
import {Edit} from '@element-plus/icons-vue'


const validateConfirmPassword = (rule, value, callback) => {
  if (value !== state.resetPwdDialog.form.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
}

const state = reactive({
  isLoading: false,
  tableData: [],
  pager: {
    currentPage: 1,
    totalCount: 0,
    perPageSize: 10,
    handleSizeChange: handleSizeChange,
    handleChangePage: handleChangePage
  },
  editId: -1,
  editIndex: -1,
  userAddDialog: {
    visible: false,
    title: "",
    form: {
      username: "",
      password: "",
      confirm_password: "",
      is_super: false,
      roles: []
    },
    errors: {
      username: "",
      password: "",
      confirm_password: "",
      is_super: "",
      roles: ""
    },
    fields: [
      {name: 'username', label: '用户名', wiget: 'input'},
      {name: 'password', label: '密码', wiget: 'password'},
      {name: 'confirm_password', label: '确认密码', wiget: 'password'},
      {name: 'is_super', label: '超级用户', wiget: 'switch'},
      {name: 'roles', label: '角色', wiget: 'checkbox'},
    ],
    options: {
      roles: []
    },
    doSubmit: doUserSubmit
  },

  userEditDialog: {
    visible: false,
    title: "",
    form: {
      username: "",
      is_super: false,
      roles: []
    },
    errors: {
      username: "",
      is_super: "",
      roles: ""
    },
    fields: [
      {name: 'username', label: '用户名', wiget: 'input'},
      {name: 'is_super', label: '超级用户', wiget: 'switch'},
      {name: 'roles', label: '角色', wiget: 'checkbox'},
    ],
    options: {
      roles: []
    },
    doSubmit: doUserSubmit
  },

  resetPwdDialog: {
    visible: false,
    title: "",
    form: {
      password: "",
      confirmPassword: ""
    },
    errors: {
      password: "",
      confirmPassword: ""
    },
    fields: [
      {name: 'password', label: '密码', wiget: 'input'},
      {name: 'confirmPassword', label: '确认密码', wiget: 'input'},

    ],
    doSubmit: doResetPwdSubmit
  }
})
onMounted(() => {
  fetchTable(1)
})


function fetchTable(page, limit) {
  if (hasPermission2("user-list", "get")) {
    return
  }
  _axios.get("/api/web/user/", {params: {page: page, page_size: limit}}).then((res) => {
    if (res.data.code === 0) {
      state.tableData = res.data.data.data;
      state.pager.totalCount = res.data.data.totalCount;
      state.pager.perPageSize = res.data.data.perPageSize
    }
  })

}

function handleChangePage(page) {
  fetchTable(page)
}

function fetchRole() {
  _axios.get('/api/role/').then((res) => {
    if (res.data.code === 0) {
      state.userAddDialog.options.roles = res.data.data
      state.userEditDialog.options.roles = res.data.data
    }
  })
}

function doAddUser() {
  state.userAddDialog.visible = true
  state.userAddDialog.title = "添加用户"
  state.editId = -1
  state.editIndex = -1
  state.userAddDialog.errors = {}

  state.userAddDialog.form = {
    username: "",
    password: "",
    confirm_password: "",
    is_super: false,
    roles: []
  }
  fetchRole()

}

function confirmUserDelete(row) {
  _axios.delete(`/api/user/${row.id}/`).then((res) => {
    if (res.data.code === 0) {
      state.tableData = state.tableData.filter((item) => {
        return row.id !== item.id
      })
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
  })
}

function doUserEdit(row, index) {
  state.userEditDialog.errors = {}
  state.userEditDialog.visible = true
  state.userEditDialog.title = '编辑用户'
  state.editId = row.id
  state.editIndex = index
  fetchRole()
  let userDict = state.tableData[index]
  state.userEditDialog.form = {
    username: userDict.username,
    is_super: userDict.is_super,
    roles: userDict.roles
  }

}

function doUserSubmit() {
  if (state.editId > 0) {
    state.userEditDialog.errors = {}
    _axios.patch(`/api/user/${state.editId}/`, state.userEditDialog.form).then((res) => {
      if (res.data.code === 0) {
        state.tableData[state.editIndex] = res.data.data
        state.editId = -1
        state.editIndex = -1
        state.userEditDialog.visible = false
      } else if (res.data.code === 2001) {
        for (let key in res.data.detail) {
          state.userEditDialog.errors[key] = res.data.detail[key][0]
        }
      } else {
        ElMessage.error("编辑失败")
      }
    })
  } else {
    state.userAddDialog.errors = {}
    _axios.post('/api/user/', state.userAddDialog.form).then((res) => {
      if (res.data.code === 0) {
        state.tableData.unshift(res.data.data)
        state.userAddDialog.form = {
          username: "",
          password: "",
          confirm_password: "",
          is_super: false,
          roles: []
        }
        state.userAddDialog.visible = false
      } else if (res.data.code === 2001) {
        for (let key in res.data.detail) {
          state.userAddDialog.errors[key] = res.data.detail[key][0]
        }
      } else {
        ElMessage.error("添加失败")
      }
    })
  }
}

function doResetPwd() {

}

function doResetPwdSubmit() {

}


</script>

<style scoped>

</style>